package com.dinghui.pay.controller.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.dinghui.pay.common.ResponseResult;
import com.dinghui.pay.pojo.TbOrder;
import com.dinghui.pay.pojo.TbUser;
import com.dinghui.pay.pojo.param.PayOrderParam;
import com.dinghui.pay.pojo.param.ScanCodePayOrderParam;
import com.dinghui.pay.pojo.param.UpdateNativeOrderStatusParam;
import com.dinghui.pay.service.OrderService;
import com.dinghui.pay.service.UserService;
import com.dinghui.pay.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-06-05 19:46
 */
// 支付宝付款码 业务接口
@RestController
@RequestMapping("/api/alipay/scanCode")
public class ScanCodeController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private OrderService orderService;

    @Value("${alipay.app.app-id}")
    private String app_appId;

    @Value("${alipay.app.public-key}")
    private String app_publicKey;

    @Value("${alipay.app.private-key}")
    private String app_privateKey;

    @Value("${alipay.microApp.gateway}")
    private String gateway;

    /**
     * ScanCode 接口调用 :https://opendocs.alipay.com/open/194/106039
     *
     * 创建支付订单关键参数
     * out_trade_no: 商品订单编号
     * scene: 支付场景
     * auth_code: 付款码
     * subject: 商品标题
     * body: 订单备注
     * total_amount: 订单金额
     * timeout_express: 过期时间
     */

    /**
     * ScanCode付款
     * 支付宝付款码的规则：
     * 支付宝付款码必须是25-30开头的数字，一共16到24位数字组成 正则：^(25|26|27|28|29|30)[0-9]{14,22}$
     * 微信付款码必须是10-15开头的数字，一共18位数字组成 正则：^1[0-5][0-9]{16}$
     */
    @PostMapping("/scanCodePayOrder")
    public ResponseResult scanCodePayOrder(@RequestBody ScanCodePayOrderParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbUser user = new TbUser();
        user.setUserId(userId);
        long count = userService.getCount(user);
        //判断用户是否存在
        if (count == 0) {
            return ResponseResult.error("用户不存在");
        }

        //判断用户是否拥有这个订单，并且订单是未支付状态
        TbOrder order = new TbOrder();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("不是有效的订单");
        }

        // todo 验证购物券是否有效
        // todo 验证团购活动是否有效

        //查询订单详情信息
        order = new TbOrder();
        order.setId(orderId);
        order = orderService.getOne(order); //订单对象
        String amount = order.getAmount() + ""; //订单金额

        try {
            AlipayClient client = new DefaultAlipayClient(
                    gateway,
                    app_appId,
                    app_privateKey,
                    "json",
                    "UTF-8",
                    app_publicKey,
                    "RSA2"
            );
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            request.setBizContent("{" +
                    "    \"out_trade_no\":\"" + order.getCode() + "\"," +
                    "    \"scene\":\"bar_code\"," +
                    "    \"auth_code\":\"" + param.getAuthCode() + "\"," +
                    "    \"subject\":\"扫码付款测试\"," +
                    "    \"store_id\":\"NJ_001\"," +
                    "    \"timeout_express\":\"2m\"," +
                    "    \"total_amount\":\"" + amount + "\"" +
                    "  }");
            AlipayTradePayResponse response = client.execute(request);
            if (response.isSuccess() && response.getCode().equals("10000")) {
                //更新本地商品订单信息，但是不更新商品订单状态
                String prepayId = response.getTradeNo();
                order.setPrepayId(prepayId);
                order.setStatus(2);
                order.setPaymentType(2); //支付类型
                order.setId(order.getId());  // 查询条件
                orderService.update(order);
                return ResponseResult.success("付款成功");
            } else {
                return ResponseResult.error("付款失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("支付宝支付模块故障");
        }
    }



}